package com.fingard.dsp.bank.directbank.pab01;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.ReceiptFileSaveHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class PAB01Receipt extends PAB01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        if (this.getBankConfig().getValueAsBool("receiptUploadShared")) {
            String receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
            if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                        PAB01SyncTask tmpTask = new PAB01SyncTask(p_reqReceipt, this);
                        tmpTask.downloadReceipt();
                        retAts.respCode = "0";
                        retAts.respInfo = "后台处理中";

                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "DSPSystem未配置回单文件推送地址";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "DSPSystem未配置回单文件共享目录";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "DSPSystem未配置回单文件下载保存主目录";
            }
            retAts.writeRetToATS();
            return retAts;
        } else {
            try {
                Calendar tmpCalendarFrom = Calendar.getInstance();
                tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

                Calendar tmpCalendarTo = Calendar.getInstance();
                tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

                int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

                //按日循环
                while (tmpIntFrom <= tmpIntTo) {//按日查询
                    int intFromStep = tmpIntFrom;
                    Date fromDateStep = tmpCalendarFrom.getTime();
                    WriteBankLogLn("执行" + intFromStep + "的回单数据查询");
                    qryReceiptByOneDay(p_reqReceipt, fromDateStep);
                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                }
            } catch (Exception ex) {
                retAts.respCode = "-1";
                retAts.respInfo = LogHelper.getStackTrace(ex);
                WriteBankLogLn(ex);
            }

            retAts.writeRetToATS();
            return retAts;
        }
    }

    public void qryReceiptByOneDay(ReqQryReceipt p_reqReceipt, Date pOneDay) throws Exception {

        XmlTextWriter resultWriter = new XmlTextWriter();
        resultWriter.writeStartElement("Result");
        PAB01Header bankHeader = new PAB01Header();
        bankHeader.trncode = "ELC001";
        bankHeader.fourZero = "0000";
        int recordNum = getBankConfig().getValueAsInt("recordNum", 200, "receipt");//每页记录数
        int startRecord = 1;//起始值为1，不能送0
        String respCode = "0";
        String respInfo = "";
        String endFlag = "N";//Y:无剩余记录  N:有剩余记录
        boolean tmpQryNext = true;
        while (tmpQryNext && "0".equals(respCode) && !"Y".equals(endFlag)) {//分页查询
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("Result");
            xmlWriter.writeElementString("AcctNo", p_reqReceipt.actNum);
            xmlWriter.writeElementString("ReceiptType", "ALL");//回单类型
            xmlWriter.writeElementString("SubType", "ALL");//子类型
            xmlWriter.writeElementString("StartDate", Format.Date8Format.format(pOneDay));//起始日期 格式yyyyMMdd（记账日期）
            xmlWriter.writeElementString("EndDate", Format.Date8Format.format(pOneDay));//结束日期
            xmlWriter.writeElementString("StartRecord", startRecord + "");//起始值为1，不能送0
            xmlWriter.writeElementString("RecordNum", recordNum + "");//本批记录数
            xmlWriter.writeElementClosed("StartAmt");//非必输，开始金额
            xmlWriter.writeElementClosed("EntAmt");//非必输，结束金额
            /*001：交易时间从近到远   002：交易时间从远到近   003：金额升序（从小到大）   004：金额降序（从大到小）   005：回单号升序   006：回单号降序*/
            xmlWriter.writeElementClosed("OrderMode");//非必输，排序方式
            xmlWriter.writeElementClosed("PayeeAcctNo");//非必输，收款人账号
            xmlWriter.writeElementClosed("PayeeName");//非必输，收款人名称
            xmlWriter.writeElementClosed("DrCrFlag");//非必输，借贷标志
            xmlWriter.writeElementClosed("Ccy");//非必输，币种
            xmlWriter.writeElementClosed("SerialNo");//非必输，顺序号
            xmlWriter.writeElementClosed("PrintBranchId");//非必输，打印网点
            xmlWriter.writeElementClosed("ReceiptNo");//非必输，回单号
            xmlWriter.writeElementClosed("PrintFlag");//非必输，打印标志，0：首次打印      1：补打
            xmlWriter.writeEndDocument();
            bankHeader.reqSeqNo = getQryTransID();
            WriteBankLogLn("发送银行报文:\r\n:" + xmlWriter.toXmlString());
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
            WriteBankLogLn("银行返回结果:\r\n:" + tmpStrRet);
            if (tmpStrRet[0].length() == 0 && StringHelper.hasAnyChar(tmpStrRet[1])) {
                String retCode = tmpStrRet[2];
                String retInfo = tmpStrRet[3];
                if ("000000".equals(retCode)) {
                    if (tmpStrRet[1].contains("<")) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                        if (tmpBkReader != null) {
                            //Y:无剩余记录  N:有剩余记录
                            endFlag = tmpBkReader.getFirstText("/Result/EndFlag").toUpperCase();
                            p_reqReceipt.receiptNo = tmpBkReader.getFirstText("/Result/list/ReceiptNo");
                            int totalCount = 0;
                            String rdTotalCount = tmpBkReader.getFirstText("/Result/RecordTotalCount");//记录总数
                            if (StringHelper.hasAnyChar(rdTotalCount)) {
                                totalCount = Integer.parseInt(rdTotalCount);
                            }

                            if (totalCount <= 0) {
                                tmpQryNext = false;
                                respCode = "-1";
                                respInfo = "记录总数为0";
                            } else {
                                int cmpStartRecord = 0;
                                String bkStartRecord = tmpBkReader.getFirstText("/Result/StartRecord");//起始记录数
                                if (StringHelper.hasAnyChar(bkStartRecord)) {
                                    cmpStartRecord = Integer.parseInt(bkStartRecord);
                                }
                                if (cmpStartRecord != startRecord) {
                                    tmpQryNext = false;
                                    respCode = "-1";
                                    respInfo = "响应起始记录数" + bkStartRecord + "与请求" + startRecord + "不一致";
                                } else {
                                    int addResultNum = 0;
                                    String bkResultNum = tmpBkReader.getFirstText("/Result/ResultNum");//本次返回记录数
                                    if (StringHelper.hasAnyChar(bkResultNum)) {
                                        addResultNum = Integer.parseInt(bkResultNum);
                                    }
                                    if (addResultNum > 0) {
                                        startRecord += addResultNum;//继续查询

                                        while (tmpBkReader.read("/Result/list")) {
                                            resultWriter.writeXElement(tmpBkReader.readedXElement);
                                        }

                                    } else {
                                        tmpQryNext = false;
                                        respCode = "-1";
                                        respInfo = "本次返回记录数为" + bkResultNum;
                                    }
                                }
                            }
                        } else {
                            respCode = "-1";
                            respInfo = tmpSbMsg.toString();
                        }
                    } else {
                        respCode = "-1";
                        respInfo = "银行返回报文格式非法";
                    }
                } else {
                    respCode = "-1";
                    respInfo = retInfo;
                }
            } else {
                respCode = "-1";
                respInfo = tmpStrRet[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "银行响应内容为空";
                }
                break;
            }
        }
        if ("0".equals(respCode)) {
            resultWriter.writeEndDocument();
            DataFileHelper dFileHelper = new DataFileHelper(this);
            String dataFilePath = dFileHelper.getBankReceiptDataFile(pOneDay, p_reqReceipt.actNum);
            File dataFile = new File(dataFilePath);
            if (dataFile.exists()) {
                this.WriteBankLogLn("回单数据文件" + dataFilePath + "已存在，先删除再重新写入");
                dataFile.delete();
            }
            FileHelper.writeFile(dataFilePath, resultWriter.toXmlString(), FGBiz.dspCenter.charset);
            qryReceiptFile(p_reqReceipt, pOneDay);
        } else {
            this.WriteBankLogLn("查询回单数据失败：" + respCode + "-" + respInfo);
        }
    }

    private void qryReceiptFile(ReqQryReceipt p_reqReceipt, Date pOneDay) throws Exception {
        PAB01Header bankHeader = new PAB01Header();
        bankHeader.trncode = getBankConfig().getValueAsString("receiptTransCode", "ELC002");
        bankHeader.fourZero = "0000";
        bankHeader.reqSeqNo = getQryTransID();
        XmlTextWriter xmlWriter = new XmlTextWriter();
        xmlWriter.autoFormat = false;
        writeCommonHeader(xmlWriter);
        xmlWriter.writeStartElement("Result");
        xmlWriter.writeElementString("Account", p_reqReceipt.actNum);
        xmlWriter.writeElementString("QueryDate", Format.Date8Format.format(pOneDay));
        //xmlWriter.writeElementString("BsnCode", "");
        xmlWriter.writeEndDocument();
        WriteBankLogLn("发送银行报文:\r\n:" + xmlWriter.toXmlString());
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader);
        WriteBankLogLn("银行返回结果:\r\n:" + tmpStrRet);
        boolean isAllRight = true;
        if (tmpStrRet[0].length() == 0 && StringHelper.hasAnyChar(tmpStrRet[1])) {
            String retCode = tmpStrRet[2];
            //String retInfo = tmpStrRet[3];
            if ("000000".equals(retCode)) {
                if (tmpStrRet[1].contains("<")) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                    if (tmpBkReader != null) {
                        DownloadFile download = new DownloadFile(this.reqHeader, this.bankFront, this.sbLog);
                        if ("ELC002".equals(bankHeader.trncode)) {
                            while (tmpBkReader.read("/Result")) {
                                /**  <list>
                                 <FileName>11002923034501_4004_20190429.txt</FileName>
                                 <FilePath>
                                 </FilePath>
                                 <RandomPwd>BLVJ5dXM39lorcmw/puCquJ4UGY9GJ2j</RandomPwd>
                                 <SignData>
                                 </SignData>
                                 <HashData>
                                 </HashData>
                                 </list>*/
                                DownFileReq req = new DownFileReq(tmpBkReader.readedXElement);
                                //req.filePath="/afe_ftp/00303079800000117000";
                                req.filePath = bankFront.bkTransFolder;
                                //下载文件
                                DownFileResp resp = download.downFile(req);
                                if (resp.execResult) {
                                    ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
                                    DataFileHelper dFileHelper = new DataFileHelper(this);
                                    File receiptDir = new File(bankFront.bankReceiptMainDir);
                                    if (!receiptDir.exists()) {
                                        WriteBankLogLn("不存在平安回单目录" + bankFront.bankReceiptMainDir);
                                        return;
                                    }
                                    String filePath = StringHelper.trimEnd(bankFront.bankReceiptMainDir, "/");
                                    String[] PathName = req.fileName.split("\\.");
                                    WriteBankLogLn("文件下载已完成，开始解压...");
                                    WriteBankLogLn("解压至：[" + filePath + "]");
                                    ZipHelper.unzipFile(filePath + File.separator + req.fileName, filePath);
                                    WriteBankLogLn("文件解压已完成");
                                    //获取前置目录全部回单文件
                                    filePath = filePath + File.separator + PathName[0];
                                    File depressDir = new File(filePath);
                                    if (depressDir.exists()) {
                                        File[] receiptFiles = depressDir.listFiles();
                                        if (receiptFiles == null && receiptFiles.length == 0) {
                                            WriteBankLogLn("文件夹" + filePath + "下为空");
                                        }
                                        int delCount = 0;
                                        for (File receiptFile : receiptFiles) {
                                            String eachName = receiptFile.getName();
                                            if (eachName.toLowerCase().endsWith(".pdf")) {
                                                String[] filenameSpliter = eachName.split("_");
                                                String localSavePath = filePath + File.separator + eachName;
                                                ReceiptMapping eachRcptMp = new ReceiptMapping();
                                                eachRcptMp.busRef = p_reqReceipt.receiptNo;
                                                String otherBusRef = "";
                                                WriteBankLogLn("取出的流水号为：" + filenameSpliter[2].trim());
                                                int idxDot = filenameSpliter[2].lastIndexOf(".");
                                                if (idxDot > 0) {
                                                    otherBusRef = filenameSpliter[2].substring(0, idxDot);
                                                } else {
                                                    otherBusRef = filenameSpliter[2];
                                                }
                                                eachRcptMp.addOtherBusRef(otherBusRef, otherBusRef);
                                                eachRcptMp.bank = "307";
                                                eachRcptMp.setBusDate(p_reqReceipt.getDateFrom());
                                                eachRcptMp.ownAct = p_reqReceipt.actNum;
                                                eachRcptMp.keyName = "receiptNo";
                                                eachRcptMp.amount = new BigDecimal("0.00");
                                                eachRcptMp.receiptNo = filenameSpliter[2].trim();
                                                eachRcptMp.srcFile = eachName;
                                                eachRcptMp.amount = new BigDecimal(0);
                                                HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, filePath + File.separator + eachName);
                                                WriteBankLogLn(saveResp.sbMsg);
                                                if (saveResp.isCompleted) {
                                                    File toDel = new File(localSavePath);
                                                    WriteBankLogLn("删除文件" + toDel.getName());
                                                    toDel.delete();
                                                    delCount++;
                                                } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                                    WriteBankLogLn("连接服务器失败，终止本次推送");
                                                    isAllRight = false;
                                                    break;
                                                } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                                    WriteBankLogLn(ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送");
                                                    break;
                                                }
                                            }
                                        }
                                        if (FileHelper.deleteFileIfExists(filePath)) {
                                            WriteBankLogLn("已删除文件夹：" + filePath);
                                        }
                                        if (!isAllRight) {
                                            break;
                                        }
                                        WriteBankLogLn("成功删除了" + delCount + "个文件");
                                    }
                                } else {
                                    WriteBankLogLn("下载文件失败，路径" + req.filePath + "文件名" + req.fileName + "：" + resp.execMsg);
                                }
                            }
                        } else {//F00101
                            while (tmpBkReader.read("/Result/list")) {
                                /**  <list>
                                 <FileName>11002923034501_4004_20190429.txt</FileName>
                                 <FilePath>
                                 </FilePath>
                                 <RandomPwd>BLVJ5dXM39lorcmw/puCquJ4UGY9GJ2j</RandomPwd>
                                 <SignData>
                                 </SignData>
                                 <HashData>
                                 </HashData>
                                 </list>*/
                                DownFileReq req = new DownFileReq(tmpBkReader.readedXElement);
                                //req.filePath="/afe_ftp/00303079800000117000";
                                req.filePath = bankFront.bkTransFolder;
                                //下载文件
                                DownFileResp resp = download.downFile(req);
                                if (resp.execResult) {
                                    ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
                                    DataFileHelper dFileHelper = new DataFileHelper(this);
                                    File receiptDir = new File(bankFront.bankReceiptMainDir);
                                    if (!receiptDir.exists()) {
                                        WriteBankLogLn("不存在平安回单目录" + bankFront.bankReceiptMainDir);
                                        return;
                                    }
                                    String filePath = StringHelper.trimEnd(bankFront.bankReceiptMainDir, "/");
                                    String[] PathName = req.fileName.split("\\.");
                                    WriteBankLogLn("文件下载已完成，开始解压...");
                                    WriteBankLogLn("解压至：[" + filePath + "]");
                                    ZipHelper.unzipFile(filePath + File.separator + req.fileName, filePath);
                                    WriteBankLogLn("文件解压已完成");
                                    //获取前置目录全部回单文件
                                    filePath = filePath + File.separator + PathName[0];
                                    File depressDir = new File(filePath);
                                    if (depressDir.exists()) {
                                        File[] receiptFiles = depressDir.listFiles();
                                        if (receiptFiles == null && receiptFiles.length == 0) {
                                            WriteBankLogLn("文件夹" + filePath + "下为空");
                                        }
                                        int delCount = 0;
                                        for (File receiptFile : receiptFiles) {
                                            String eachName = receiptFile.getName();
                                            if (eachName.toLowerCase().endsWith(".pdf")) {
                                                String[] filenameSpliter = eachName.split("_");
                                                String localSavePath = filePath + File.separator + eachName;
                                                ReceiptMapping eachRcptMp = new ReceiptMapping();
                                                eachRcptMp.busRef = p_reqReceipt.receiptNo;
                                                String otherBusRef = "";
                                                WriteBankLogLn("取出的流水号为：" + filenameSpliter[2].trim());
                                                int idxDot = filenameSpliter[2].lastIndexOf(".");
                                                if (idxDot > 0) {
                                                    otherBusRef = filenameSpliter[2].substring(0, idxDot);
                                                } else {
                                                    otherBusRef = filenameSpliter[2];
                                                }
                                                eachRcptMp.addOtherBusRef(otherBusRef, otherBusRef);
                                                eachRcptMp.bank = "307";
                                                eachRcptMp.setBusDate(p_reqReceipt.getDateFrom());
                                                eachRcptMp.ownAct = p_reqReceipt.actNum;
                                                eachRcptMp.keyName = "receiptNo";
                                                eachRcptMp.amount = new BigDecimal("0.00");
                                                eachRcptMp.receiptNo = filenameSpliter[2].trim();
                                                eachRcptMp.srcFile = eachName;
                                                eachRcptMp.amount = new BigDecimal(0);
                                                HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, filePath + File.separator + eachName);
                                                WriteBankLogLn(saveResp.sbMsg);
                                                if (saveResp.isCompleted) {
                                                    File toDel = new File(localSavePath);
                                                    WriteBankLogLn("删除文件" + toDel.getName());
                                                    toDel.delete();
                                                    delCount++;
                                                } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                                    WriteBankLogLn("连接服务器失败，终止本次推送");
                                                    isAllRight = false;
                                                    break;
                                                } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                                    WriteBankLogLn(ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送");
                                                    break;
                                                }
                                            }
                                        }
                                        if (FileHelper.deleteFileIfExists(filePath)) {
                                            WriteBankLogLn("已删除文件夹：" + filePath);
                                        }
                                        if (!isAllRight) {
                                            break;
                                        }
                                        WriteBankLogLn("成功删除了" + delCount + "个文件");
                                    }
                                } else {
                                    WriteBankLogLn("下载文件失败，路径" + req.filePath + "文件名" + req.fileName + "：" + resp.execMsg);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

